package com.example.hanfu.firstpage;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.bumptech.glide.Glide;
import com.example.hanfu.R;
import com.example.hanfu.WebViewActivity;
import com.example.hanfu.collect.Collect;
import com.example.hanfu.collect.CollectDBmanager;
import com.example.hanfu.login.LoginActivity;
import com.example.hanfu.login.LoginState;
import com.stx.xhb.xbanner.XBanner;
import com.stx.xhb.xbanner.transformers.Transformer;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ShouYeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ShouYeFragment extends Fragment implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
    private static final String TAG = "ShouYeFragment";
    ListView listView;
    HanFuAdapter adapter;
    private XBanner xBanner;
    LoginState loginState=new LoginState();
    CollectDBmanager manager;

    List<HanFu> ret;
    final List<String> imgesUrl = new ArrayList<>();
    public ShouYeFragment() {
        // Required empty public constructor
    }


    // TODO: Rename and change types and number of parameters
    public static ShouYeFragment newInstance() {
        ShouYeFragment fragment = new ShouYeFragment();

        fragment.setRetainInstance(true);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_shou_ye, container, false);
    }
@Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        manager=new CollectDBmanager(getContext());
        super.onViewCreated(view, savedInstanceState);
        listView = view.findViewById(R.id.mylist3);
        xBanner= view.findViewById(R.id.banner1);
        ProgressBar progressBar = view.findViewById(R.id.progressBar);

        listView.setOnItemClickListener(this);
        listView.setOnItemLongClickListener(this);




        Handler handler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 11) {
                    adapter = new HanFuAdapter(getContext(), R.layout.list_item, (ArrayList
                            <HanFu>) msg.obj);
                    listView.setAdapter(adapter);
                    imgesUrl.add("https://hanfusong.com/wp-content/themes/mnews/includes/timthumb.php?src=https://hanfusong.com/wp-content/uploads/2021/01/2021010922443024-scaled.jpg&h=280&w=460");
                   // titles.add("1hhhhhhhhhhh");
                    imgesUrl.add("https://hanfusong.com/wp-content/themes/mnews/includes/timthumb.php?src=https://hanfusong.com/wp-content/uploads/2020/03/23/hanfu0-1584943914.jpeg&h=280&w=460");
                    imgesUrl.add("https://hanfusong.com/wp-content/themes/mnews/includes/timthumb.php?src=https://hanfusong.com/wp-content/uploads/2021/01/2021010921313277.jpg&h=280&w=460");
                    //titles.add("3klljjhh");
                    //imgesUrl.add("http://imageprocess.yitos.net/images/public/20160906/1291473163104906.jpg");
                    xBanner.setData(imgesUrl,null);
                    //图片加载
                    xBanner.loadImage(new XBanner.XBannerAdapter() {
                        @Override
                        public void loadBanner(XBanner banner,
                                               Object model, View view, int position) {
                            //glide请求网络图片
                            Glide.with(ShouYeFragment.this)
                                    .load(imgesUrl.get(position))
                                    .into((ImageView) view);
                        }
                    });

                    // 设置XBanner的页面切换特效，有多个，其他的可以到网上去查
                    xBanner.setPageTransformer(Transformer.Default);//横向移动
                    xBanner.setVisibility(View.VISIBLE);

                    //显示隐藏
                    listView.setVisibility(View.VISIBLE);
                    progressBar.setVisibility(View.GONE);
                }
                super.handleMessage(msg);
            }
        };
        FirstTask task = new FirstTask();
        task.setHandler(handler);
        Thread t=new Thread(task);
        t.start();




    xBanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
        @Override
        public void onItemClick(XBanner banner, Object model,View view, int position) {
            String href="";
            if(position==0){
                href="https://hanfusong.com/topic/66335";
            }else if(position==1){
                href="https://hanfusong.com/archives/1843.html";
            }else if(position==2){
                href="https://hanfusong.com/topic/66334";
            }
            Intent openHref=new Intent(getContext(), WebViewActivity.class)
                    .putExtra("url",href);
            Log.i(TAG, "openWebViewActivity:url=" + href);
            startActivity(openHref);

        }
    });

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        HanFu item =(HanFu) listView.getItemAtPosition(position);
        //判断是否登录
        if(loginState.getLogin_state()!=0){
            //加入历史记录
            Collect collect=new Collect(loginState.getUserName(),item);
            manager.add(collect,"history");
            Log.i(TAG,"添加数据库,当前用户名为："+loginState.getUserName());
        }
        String title=item.getTitle();
        String href=item.getHref();
        //Bitmap img=item.getImg();
        Log.i(TAG, "onItemClick:title" + title);
        Log.i(TAG, "onItemClick:href:" + href);
        //Log.i(TAG, "onItemClick:img:" + img);
        Intent openHref=new Intent(getContext(),WebViewActivity.class)
                .putExtra("url",href);
        Log.i(TAG, "openWebViewActivity:url=" + href);
        startActivity(openHref);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        Log.i(TAG, "长按事件 position=" + position);
        HanFu item =(HanFu) listView.getItemAtPosition(position);
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        if(loginState.getLogin_state()==0){
            new AlertDialog.Builder(getContext())
                    .setTitle("提示")
                    .setMessage("请先登录")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //已登录
                            Intent score = new Intent(getContext(), LoginActivity.class);//窗口对象
                            startActivity(score);

                        }}).setNegativeButton("取消",null).show();

        }else {
            //收藏
            builder.setTitle("提示")
                    .setMessage("收藏成功")
                    .setPositiveButton("确定",null).show();
            Collect collect=new Collect(loginState.getUserName(),item);
            manager.add(collect,"collect");
            Log.i(TAG,"添加数据库,当前用户名为："+loginState.getUserName());
        }

        //adapter.remove(item);
        return true;//false:长按后会触发单击事件
    }

}


